import React, {useEffect, useState} from 'react';
import makeStyles from "@material-ui/core/styles/makeStyles";
import {useLocation} from 'react-router-dom'
import axios from 'axios'
import {BASE_URL, NOT_FOUND_ERROR_MESSAGE, SERVER_ERROR_MESSAGE} from "../constants";
import BaseBookList from "./BaseBookList";
import LoadingSpinner from "../components/LoadingSpinner";
import InlineError from "../components/InlineError";
import EmptyResultsMessages from "../components/EmptyResultsMessages";

const useStyles = makeStyles(theme => ({
    root: {
        padding: theme.spacing(2)
    },
}))


export default function MostBooks() {
    const classes = useStyles()
    const location = useLocation()

    const [state, setState] = useState({
        books: [],
        error: '',
        loading: true,
    })

    async function fetchBooks(url) {
        try {
            const response = await axios.get(url)
            const data = await response.data
            setState(prevState => ({...prevState, loading: false, books: data}))
        } catch (err) {
            if (err.response && err.response.status === 404)
                setState(prevState => ({...prevState, loading: false, error: NOT_FOUND_ERROR_MESSAGE, books: []}))
            else
                setState(prevState => ({...prevState, loading: false, error: SERVER_ERROR_MESSAGE, books: []}))
        }
    }

    useEffect(() => {
        fetchBooks(`${BASE_URL}${location.pathname}/`)
    }, [location.pathname])

    const {books, loading, error} = state

    if (loading) return <div className={classes.root}><LoadingSpinner/></div>
    if (error) return <div className={classes.root}><InlineError error={error}/></div>
    if (books.length === 0) return <div className={classes.root}><EmptyResultsMessages/></div>

    return <BaseBookList books={books}/>
};
